package com.consumer.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: springcloud
 * @description:
 * @author: zfy
 * @create: 2020-08-18 18:10
 */
@Component
@Configuration
public class MyLB implements LoadBalancer {
//    创建一个元子类
    private AtomicInteger atomicInteger=new AtomicInteger(0);
//    获取访问次数
    public  final  int getAtomicInteger(){
        int current;
        int next;
        do {
            current=this.atomicInteger.get();
            int maxValue = Integer.MAX_VALUE;
            next=current>=maxValue? 0:current+1;
//            利用CAS自旋锁获取次数   当期望值（current）  与返回值（next）相同是返回 true
        }while (!atomicInteger.compareAndSet(current,next));
        System.out.println("第几次访问，当前次数："+next);
        return next;

    }


    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
//        通过  用服务总数对访问次数取余 获取提供服务的下标
        int index=getAtomicInteger()% serviceInstances.size();
//        返回 提供服务的 服务实例
        return serviceInstances.get(index);
    }
}